import {
  searchDevs,
  closeSearchDevs,
  readIdCard,
  searchDevsImmediately,
  autoReadIdCard,
  connectDevs} from './idCardRead'

// pages/boxIndex/boxIndex.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSearching:false,
    devices:[],
    connectDev:null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  //搜索设备
  doSearchDevs:async function(){
   
    wx.showLoading({
      title: '查询中',
    })

   //查询为true
   this.setData({isSearching:true})

    // //查询设备
    // await searchDevs( devices => {
    //   this.setData({
    //     devices
    //   })
    // })

    // //限时10S关闭搜索
    // setTimeout(async ()=>{
    //   await this.doCloseSearchDevs()
    // },1000*10);

    //找到设备立即返回
    const devices = await searchDevsImmediately()

    this.setData({devices,isSearching:false})

    wx.hideLoading({
      success: (res) => {},
    })

  },
  //关闭蓝牙搜索
  doCloseSearchDevs:async function(){
    const {isSearching} = this.data;
    if(isSearching){
      await closeSearchDevs()
      wx.hideLoading({})
      this.setData({
        isSearching:false
      })
    }
  },
  //连接设备
  doConnect:async function(e){
    const {devices} = this.data;
    const {devid} = e.currentTarget.dataset

    wx.showToast({
      title: '连接中',
    })

    const targetDev = devices.find(v => v.deviceId == devid)

    const connectDevice = await connectDevs(targetDev)

    wx.showToast({
      title: '连接成功',
    })

    const devicesNew = devices.map(v => {
        if(v.deviceId == devid){
          this.setData({connectDevice})   
          return connectDevice;       
        }
        return v
    })

    this.setData({
      devices:devicesNew
    })

  },
  readIdCard:async function(){
    const {connectDevice} = this.data;
    const idCardInfo = await readIdCard(connectDevice)
    console.log({idCardInfo})
  },
  autoRead:async function(){
    const idCard = await autoReadIdCard()
    console.log("身份证:",idCard);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})